package com.manage.platform.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.DateUtils;
import com.manage.platform.exception.CommonException;
import com.manage.platform.properties.StorageConfig;
import com.manage.platform.vo.FileUploadVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * YWD
 * 2025/11/18
 */
@Slf4j
@AllArgsConstructor
@Service
public class FileServiceImpl {

    private final StorageConfig storageConfig;

    public FileUploadVo uploadFile(MultipartFile file) {
        if (ObjectUtil.isEmpty(file)) {
            throw new CommonException("文件为空，请重新上传！");
        }
        String uploadPath = storageConfig.getLocal().getPath();
        String url = storageConfig.getLocal().getUrl();
        if (!"/".equals(uploadPath.substring(uploadPath.length() - 1))) {
            uploadPath += "/";
        }
        String dayStr = DateUtils.format(new Date(), "yyyy-MM-dd");
        uploadPath += dayStr;
        try {
            // 确保目录存在
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
            // 保存文件（生成唯一文件名避免覆盖）
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            //String fileName = UUID.randomUUID() + fileExtension;
            int code = (int) (Math.random() * 1000000);
            String fileName = code + fileExtension;
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            FileUploadVo res = new FileUploadVo();
            res.setName(file.getOriginalFilename());
            res.setUrl(url + "/" + fileName);
            res.setSize(file.getSize());
            return res;
        } catch (IOException e) {
            log.error("文件上传失败, {}", e.getMessage());
            throw new CommonException("文件上传失败");
        }
    }



}
